import logging
import os, pdb, xlrd
import time, json, requests

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import JsonResponse
from pprint import pprint
from conf.sysConfig import config
from software.utils import fileStore, createLog
from software.utils.find_relate_duan import FindRelateDuan
from software.models import Software, SoftwareType, SoftwareVersion, SoftwareData, DuanInfo, PushOther
from storehouse.models import Storehouse
from user import dataCheck as da
from user.dataCheck import DataCheck
from user.models import Company, FileStore, User
from order.views.createOrder import createOrder
from order.models import SoftwareOrder
from software.views.view_download import download
from announcement.views.views_anno import createAnnouncement
from question.models import SoftwareQuestion, QuestionHandle

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")
serverInstallIp = config["serverInstallIp"]
serverInstallPort = config["serverInstallPort"]
serverPushUrl = config["serverPushUrl"]


# 查看详情
def softDetail(request, *args, **kwargs):
    """
        url    : /software/detail/',
        method : POST

        inputData: {
            token: data.token, // 用户的秘钥
            softwareVersionId: data.softversionid,//软件版本id
        },
        # 默认最新版本的
        resData: {
            'code': null,// 标志返回状态、0：成功，1：失败
            'msg': null,// 返回消息
            'softwareName': null,//
            'uploadTime': null,//
            'userName': null,//软件上传用户
            'softwareType': null,//软件类别
            'softwareState': null,//软件状态
            'softwareDetails': null,//软件描述
            'upCompany': null,//研发单位
            'size': null,//软件大小
            'iconUrl': null,//图标url
            'softUrl': null,//软件url
            'softwareDetails': null,
            'coverUrl': null,//封面url
            'versionList': [{
                'vesionId': null,//版本id
                'vesionName': null,//版本名称
            }]
            file {
                fileName
                fileUrl
            }
             'isView':[{'id':null,'lable':null,children:[{'id':null,'label':null}]
                        }],//
            'isDownload':[{'id':null,
                           'label':null,
                           children:[{'id':null,'label':null}]
                        }],//
            //////////////////增加参数//////////////////////////////////////
            'rejectReason':null,//拒绝理由
            'cost':'',//计费

            'verification':[{'fileName':null,'fileUrl':null}],//查杀证明 文件名称（需要有文件后缀xx.xxx） 文件类型

            'QAFile':[{'fileName':null,'fileUrl':null}],//QA文件 文件名称后加后缀
        }
    }

    """
    # pdb.set_trace()
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # 判断请求转发还是一层请求
    # pdb.set_trace()
    if requestParam["token"] != '':
        user = datacheck.getUser(requestParam["token"])
        userType = user.userType
        # 软件版本 软件
        softwareVersion = SoftwareVersion.objects.filter(pk=requestParam['softwareVersionId'])
        software = softwareVersion[0].software
        if software.isOwn == True:
            # 是本仓库软件
            softwareVersionItem = softwareVersion[0]

            # versionList
            versionList = []
            fileList = []
            # other Version
            versionLists = SoftwareVersion.objects.filter(software=software)
            if user.userType == '3':
                for item in versionLists:
                    if (item.isExamine == True) and (item.softwareState == '0') and (item.examineState == '1'):
                        if user.company in item.isBrowse.all():
                            version = {
                                'versionId': item.id,
                                'versionName': item.version,
                            }
                            versionList.append(version)
            elif user.userType == '1':
                for item in versionLists:
                    if item.user == user:
                        version = {
                            'versionId': item.id,
                            'versionName': item.version,
                        }
                        versionList.append(version)
            else:
                for item in versionLists:
                    version = {
                        'versionId': item.id,
                        'versionName': item.version,
                    }
                    versionList.append(version)
            # all Data
            currentVersionAllData = SoftwareData.objects.filter(softwareVersion=softwareVersion[0]).order_by(
                "-createTime")
            for currentVersionData in currentVersionAllData:
                file = {
                    'id': currentVersionData.file.id,
                    'dataId': currentVersionData.id,
                    'fileName': currentVersionData.dataName,
                    'fileUrl': download(currentVersionData.file.fileName, 'material', currentVersionData.file.filePath)[
                        1],
                }
                fileList.append(file)
            # todo 需要的是什么信息
            if softwareVersionItem.softwareState == '1':
                state = ''
            else:
                state = softwareVersionItem.examineState

            # todo now one verification
            verificationList = [
                {
                    'fileName': softwareVersionItem.verification.fileName,
                    'id': softwareVersionItem.verification.id,
                    'fileUrl': download(softwareVersionItem.verification.fileName, 'verification',
                                        softwareVersionItem.verification.filePath)[1],
                }
            ]

            # QAFile
            QAFileList = []
            for QAFileItem in softwareVersionItem.qaFile.all():
                item = {
                    'fileName': QAFileItem.fileName,
                    'id': QAFileItem.id,
                    'fileUrl': download(QAFileItem.fileName, 'QAFile',
                                        QAFileItem.filePath)[1],
                }
                QAFileList.append(item)

            if user.userType == '2':
                isViewTemp = {}
                isDownloadTemp = {}
                isView = []
                isDownload = []
                for company in softwareVersionItem.isBrowse.all():
                    if company.warZone.id in isViewTemp.keys():
                        isViewTemp[company.warZone.id]['children'].append({
                            'id': company.id,
                            'label': company.name,
                        })
                    else:
                        children = [{
                            'id': company.id,
                            'label': company.name,
                        }]
                        isViewTemp[company.warZone.id] = {
                            'children': children,
                            'label': company.warZone.name
                        }
                for company in softwareVersionItem.isDownload.all():
                    if company.warZone.id in isDownloadTemp.keys():
                        isDownloadTemp[company.warZone.id]['children'].append({
                            'id': company.id,
                            'label': company.name,
                        })
                    else:
                        children = [{
                            'id': company.id,
                            'label': company.name,
                        }]
                        isDownloadTemp[company.warZone.id] = {
                            'children': children,
                            'label': company.warZone.name
                        }
                for i in isViewTemp:
                    isView.append({
                        'id': i,
                        'label': isViewTemp[i]['label'],
                        'children': isViewTemp[i]['children']
                    })
                for i in isDownloadTemp:
                    isDownload.append({
                        'id': i,
                        'label': isDownloadTemp[i]['label'],
                        'children': isDownloadTemp[i]['children']
                    })
                data = {
                    'code': 0,
                    'msg': 'success',
                    'softwareName': softwareVersionItem.softwareName,
                    'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'userName': software.user.name,
                    'softwareType': softwareVersionItem.softwareType.softwareType,
                    'softwareState': state,
                    'softwareDetails': softwareVersionItem.updateDetails,
                    'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                    'upCompany': softwareVersionItem.designUnit.name,
                    'warZone': softwareVersionItem.designUnit.warZone.name,
                    'softList': tolist(softwareVersionItem.file.all(), True),
                    'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                        softwareVersionItem.logo.filePath)[1],
                    # 'size': softwareVersionItem.file.size,
                    # 'softUrl': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[
                    #     1],
                    'coverUrl': download(softwareVersionItem.cover.fileName, 'cover',
                                         softwareVersionItem.cover.filePath)[1],
                    'versionList': versionList,
                    'file': fileList,
                    'isOwn': 'todo',
                    'isOnline': softwareVersionItem.isOnline,
                    'isView': isView,
                    'isDownload': isDownload,
                    'storehouseName': softwareVersionItem.store.storehouseName,
                    'rejectReason': softwareVersionItem.softwareResult,
                    'cost': softwareVersionItem.cost,
                    'verification': verificationList,
                    'QAFile': QAFileList,
                    'isSeg': softwareVersionItem.isSeg,
                }
            else:
                # pdb.set_trace()
                data = {
                    'code': 0,
                    'msg': 'success',
                    'softwareName': softwareVersionItem.softwareName,
                    'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'userName': software.user.name,
                    'softwareType': softwareVersionItem.softwareType.softwareType,
                    'softwareState': state,
                    'softwareDetails': softwareVersionItem.updateDetails,
                    'isSeg': softwareVersionItem.isSeg,
                    'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                    'upCompany': softwareVersionItem.designUnit.name,
                    'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                        softwareVersionItem.logo.filePath)[1],
                    'softList': tolist(softwareVersionItem.file.all(), True),
                    # 'softUrl': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[
                    #     1],
                    # 'size': softwareVersionItem.file.size,
                    'coverUrl': download(softwareVersionItem.cover.fileName, 'cover',
                                         softwareVersionItem.cover.filePath)[1],
                    'versionList': versionList,
                    'file': fileList,
                    'isOwn': 'todo',
                    'isOnline': softwareVersionItem.isOnline,
                    'storehouseName': softwareVersionItem.store.storehouseName,
                    'warZone': softwareVersionItem.designUnit.warZone.name,
                    'deliveryType': softwareVersionItem.deliveryType,
                    'rejectReason': softwareVersionItem.softwareResult,
                    'cost': softwareVersionItem.cost,
                    'verification': verificationList,
                    'QAFile': QAFileList
                }
                # pdb.set_trace()
            logger_request.info(data)
            return JsonResponse(data)

        else:
            softwareVersionItem = softwareVersion[0]
            storeIP = softwareVersionItem.store.storeIP
            storePort = softwareVersionItem.store.storePort
            filterDict = {}
            softwareVersionID = softwareVersionItem.softwareVersionId
            filterDict['softwareVersionID'] = softwareVersionID
            filterDict['userType'] = userType
            data1 = requests.post("http://" + storeIP + ":" + storePort + "/api/software/" + 'detail/', data=filterDict)
            data = json.loads(data1.text)
            return JsonResponse(data)
    else:
        softwareVersion = SoftwareVersion.objects.filter(softwareVersionId=requestParam['softwareVersionID'])
        software = softwareVersion[0].software
        # 是本仓库软件
        softwareVersionItem = softwareVersion[0]

        # versionList
        versionList = []
        fileList = []
        # other Version
        versionLists = SoftwareVersion.objects.filter(software=software)
        if requestParam['userType'] == '3':
            for item in versionLists:
                if (item.isExamine == True) and (item.softwareState == '0') and (item.examineState == '1'):
                    if user.company in item.isBrowse.all():
                        version = {
                            'versionId': item.id,
                            'versionName': item.version,
                        }
                        versionList.append(version)
        elif requestParam['userType'] == '1':
            for item in versionLists:
                if item.user == user:
                    version = {
                        'versionId': item.id,
                        'versionName': item.version,
                    }
                    versionList.append(version)
        else:
            for item in versionLists:
                version = {
                    'versionId': item.id,
                    'versionName': item.version,
                }
                versionList.append(version)
        # all Data
        currentVersionAllData = SoftwareData.objects.filter(softwareVersion=softwareVersion[0])
        for currentVersionData in currentVersionAllData:
            file = {
                'id': currentVersionData.id,
                'fileName': currentVersionData.dataName,
                'fileUrl': download(currentVersionData.file.fileName, 'material', currentVersionData.file.filePath)[1],
            }
            fileList.append(file)
        # todo 需要的是什么信息
        if softwareVersionItem.softwareState == '1':
            state = ''
        else:
            state = softwareVersionItem.examineState

        # todo now one verification
        verificationList = [
            {
                'fileName': softwareVersionItem.verification.fileName,
                'fileUrl': download(softwareVersionItem.verification.fileName, 'verification',
                                    softwareVersionItem.verification.filePath)[1],
            }
        ]

        # QAFile
        QAFileList = []
        for QAFileItem in softwareVersionItem.qaFile.all():
            item = {
                'fileName': QAFileItem.fileName,
                'fileUrl': download(QAFileItem.fileName, 'QAFile',
                                    QAFileItem.filePath)[1],
            }
            QAFileList.append(item)

        if requestParam['userType'] == '2':
            isViewTemp = {}
            isDownloadTemp = {}
            isView = []
            isDownload = []
            for company in softwareVersionItem.isBrowse.all():
                if company.warZone.id in isViewTemp.keys():
                    isViewTemp[company.warZone.id]['children'].append({
                        'id': company.id,
                        'label': company.name,
                    })
                else:
                    children = [{
                        'id': company.id,
                        'label': company.name,
                    }]
                    isViewTemp[company.warZone.id] = {
                        'children': children,
                        'label': company.warZone.name
                    }
            for company in softwareVersionItem.isDownload.all():
                if company.warZone.id in isDownloadTemp.keys():
                    isDownloadTemp[company.warZone.id]['children'].append({
                        'id': company.id,
                        'label': company.name,
                    })
                else:
                    children = [{
                        'id': company.id,
                        'label': company.name,
                    }]
                    isDownloadTemp[company.warZone.id] = {
                        'children': children,
                        'label': company.warZone.name
                    }
            for i in isViewTemp:
                isView.append({
                    'id': i,
                    'label': isViewTemp[i]['label'],
                    'children': isViewTemp[i]['children']
                })
            for i in isDownloadTemp:
                isDownload.append({
                    'id': i,
                    'label': isDownloadTemp[i]['label'],
                    'children': isDownloadTemp[i]['children']
                })
            data = {
                'code': 0,
                'msg': 'success',
                'softwareName': softwareVersionItem.softwareName,
                'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                'userName': software.user.name,
                'softwareType': softwareVersionItem.softwareType.softwareType,
                'softwareState': state,
                'softwareDetails': softwareVersionItem.updateDetails,
                'isSeg': softwareVersionItem.isSeg,
                'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                'upCompany': softwareVersionItem.designUnit.name,
                'warZone': softwareVersionItem.designUnit.warZone.name,
                'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                    softwareVersionItem.logo.filePath)[1],
                'softList': tolist(softwareVersionItem.file.all(), True),
                # 'softUrl': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[1],
                # 'size': softwareVersionItem.file.size,
                'coverUrl': download(softwareVersionItem.cover.fileName, 'cover',
                                     softwareVersionItem.cover.filePath)[1],
                'versionList': versionList,
                'file': fileList,
                'isOwn': 'todo',
                'isOnline': softwareVersionItem.isOnline,
                'isView': isView,
                'isDownload': isDownload,
                'storehouseName': softwareVersionItem.store.storehouseName,
                'rejectReason': softwareVersionItem.softwareResult,
                'cost': softwareVersionItem.cost,
                'verification': verificationList,
                'QAFile': QAFileList
            }
        else:
            data = {
                'code': 0,
                'msg': 'success',
                'softwareName': software.softwareName,
                'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                'userName': software.user.name,
                'softwareType': softwareVersionItem.softwareType.softwareType,
                'softwareState': state,
                'softwareDetails': softwareVersionItem.updateDetails,
                'isSeg': softwareVersionItem.isSeg,
                'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                'upCompany': softwareVersionItem.designUnit.name,
                'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                    softwareVersionItem.logo.filePath)[1],
                'softList': tolist(softwareVersionItem.file.all(), True),
                # 'softUrl': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[1],
                # 'size': softwareVersionItem.file.size,
                'coverUrl': download(softwareVersionItem.cover.fileName, 'cover',
                                     softwareVersionItem.cover.filePath)[1],
                'versionList': versionList,
                'file': fileList,
                'isOwn': 'todo',
                'isOnline': softwareVersionItem.isOnline,
                'storehouseName': softwareVersionItem.store.storehouseName,
                'warZone': softwareVersionItem.designUnit.warZone.name,
                'deliveryType': softwareVersionItem.deliveryType,
                'rejectReason': softwareVersionItem.softwareResult,
                'cost': softwareVersionItem.cost,
                'verification': verificationList,
                'QAFile': QAFileList

            }
        logger_request.info(data)
        return JsonResponse(data)


# 获取软件列表
def softwarelist(request, *args, **kwargs):
    """
        url: '/software/list/',
        method: 'post',
        inputData: {
            token: data.token,//用户密钥
            page: data.page,//当前页
            maxItem: data.maxItem,//每页个数
            versionId: data.versionId,
            //不为空'',表示更改单张软件卡片版本的信息,请求返回表示页码信息的参数为''
            softwareGroup: data.softwareGroup,
            //管理人员-0:所有(包括审核已通过、未通过、未审核) 1：已删除(归档)
            //开发人员已审核(包括审核已通过0、未通过1)，2：未审核，3：归档
            //使用人员空
        },
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'totalNum': null,//检索到总条数
            //默认返回最新版本的软件信息
            'softwareList': [{
                'softwareId': null,
                'softwareName': null,
                'iconUrl': null,//软件图标
                'userName': null,//软件上传用户
                'softwareType': null,//软件类型
                'storehouseName': null,//所属的仓库名称
                'uploadTime': null,//软件上传时间
                'softwareDetails': null,//软件描述
                'isOnline'  // 是否上线
                isOwn   // 是否属于本仓库
                'size': null,//软件大小
                'softwareState': null,//软件状态（0：未审核，1：审核通过，2：未通过）,删除组返回‘’
                'vesionList': [{
                    'vesionId': null,//版本id[]
                    'vesionName': null,//[1.0,1.2...]
                }]
            }]

        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam["token"])
    # userType
    userType = user.userType
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    # 开发人员 todo 只能看本仓库的
    if userType == '1':
        filterDict['user'] = user
        # 已审核(包括审核已通过 0
        if requestParam['softwareGroup'] == '0':
            filterDict['isExamine'] = True
            filterDict['softwareState'] = '0'
            filterDict['examineState'] = '1'
            # 软件状态 0：未审核，1：审核通过，2：未通过（软件已删除组中此参数一直为‘’）
            # if requestParam['examineState'] in ['1', '2']:
            #     if requestParam['examineState'] == '1':
            #         filterDict['examineState'] = '1'
            #     else:
            #         filterDict['examineState'] = '2'
        # 1 未通过
        elif requestParam['softwareGroup'] == '1':
            filterDict['isExamine'] = True
            filterDict['softwareState'] = '0'
            filterDict['examineState'] = '2'
        # 1：未审核
        elif requestParam['softwareGroup'] == '2':
            filterDict['isExamine'] = False
            filterDict['softwareState'] = '0'
        # 归档的
        elif requestParam['softwareGroup'] == '3':
            filterDict['softwareState'] = '1'
        else:
            data = {
                'code': 1,
                'msg': 'softwareGroup Error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    # 仓库管理人员 todo 多个仓库
    elif userType == '2':
        # 0: 所有(包括审核已通过、未通过、未审核) 1：已删除
        if requestParam['softwareGroup'] == '0':
            filterDict['softwareState'] = '0'
        elif requestParam['softwareGroup'] == '1':
            filterDict['softwareState'] = '1'
        else:
            data = {
                'code': 1,
                'msg': 'softwareGroup Error',
            }
            logger_request.info(data)
            return JsonResponse(data)
        # if requestParam['storehouseId'] != '':
        #     filterDict['software__store__id'] = '1'
    # 使用人员
    elif userType == '3':
        filterDict['isBrowse'] = user.company
        filterDict['softwareState'] = '0'
        filterDict['examineState'] = '1'
        filterDict['isExamine'] = True
    else:
        data = {
            'code': 1,
            'msg': 'userType Error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    # 进行筛选
    # if requestParam['uploadStartTime'] != '' and requestParam['uploadEndTime'] != '':
    #     filterDict['uploadTime__gte'] = requestParam['uploadStartTime']
    #     filterDict['uploadTime__lte'] = requestParam['uploadEndTime']
    # if requestParam['softwareName'] != '':
    #     filterDict['software__softwareName__icontains'] = requestParam['softwareName']
    if requestParam['versionId'] == '':
        softwareVersion = SoftwareVersion.objects.filter(**filterDict).order_by('-createTime')
        softwareList = []
        # 临时存储
        softwareDict = {}
        # todo url 细节
        for softwareVersionItem in softwareVersion:
            if softwareVersionItem.software.id not in softwareDict.keys():
                # 多对多查询
                tempVersion = []
                versionList = {
                    'versionId': softwareVersionItem.id,
                    'versionName': softwareVersionItem.version
                }
                tempVersion.append(versionList)
                if softwareVersionItem.softwareState == '1':
                    state = ''
                else:
                    state = softwareVersionItem.examineState
                softwareItem = {
                    'softwareId': softwareVersionItem.software.id,
                    'softwareName': softwareVersionItem.softwareName,
                    'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                        softwareVersionItem.logo.filePath)[1],
                    'userName': softwareVersionItem.software.user.name,
                    'softwareType': softwareVersionItem.softwareType.softwareType,
                    'storehouseName': softwareVersionItem.store.storehouseName,
                    'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                    'softwareDetails': softwareVersionItem.updateDetails,
                    'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                    # 'size': softwareVersionItem.file.size,
                    'size': tolist(softwareVersionItem.file.all(), False),
                    'isOnline': softwareVersionItem.isOnline,
                    'isOwn': 'todo',
                    'softwareState': state,
                    'versionList': tempVersion,
                    'deliveryType': softwareVersionItem.deliveryType,
                    'rejectReason': softwareVersionItem.softwareResult
                }
                softwareDict[softwareVersionItem.software.id] = softwareItem
            else:
                versionList = {
                    'versionId': softwareVersionItem.id,
                    'versionName': softwareVersionItem.version
                }
                softwareDict[softwareVersionItem.software.id]['versionList'].append(versionList)
        for value in softwareDict.values():
            softwareList.append(value)
        totalNum = len(softwareList)
        result = softwareList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                       requestParam[
                                                                                                           'page'] *
                                                                                                       requestParam[
                                                                                                           'maxItem'])]
    else:
        totalNum = 1
        softwareVersion = SoftwareVersion.objects.filter(pk=requestParam['versionId'])
        softwareVersionItem = softwareVersion[0]
        if softwareVersionItem.softwareState == '1':
            state = ''
        else:
            state = softwareVersionItem.examineState
        tempVersion = []
        versionList = {
            'versionId': softwareVersionItem.id,
            'versionName': softwareVersionItem.version
        }
        tempVersion.append(versionList)
        result = [{
            'softwareId': softwareVersionItem.software.id,
            'softwareName': softwareVersionItem.softwareName,
            'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                softwareVersionItem.logo.filePath)[1],
            'userName': softwareVersionItem.software.user.name,
            'softwareType': softwareVersionItem.softwareType.softwareType,
            'storehouseName': softwareVersionItem.store.storehouseName,
            'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
            'softwareDetails': softwareVersionItem.updateDetails,
            'currentVersionDesc': softwareVersionItem.currentVersionDesc,
            # 'size': softwareVersionItem.file.size,
            'size': tolist(softwareVersionItem.file.all(), False),
            'isOnline': softwareVersionItem.isOnline,
            'isOwn': 'todo',
            'softwareState': state,
            'versionList': tempVersion,
            'deliveryType': softwareVersionItem.deliveryType,
            'rejectReason': softwareVersionItem.softwareResult
        }]

    data = {
        'code': 0,
        'msg': 'success',
        'totalNum': totalNum,
        'softwareList': result
    }
    logger_request.info(data)
    return JsonResponse(data)


# 软件审核、删除、恢复、发布、下线、下载
def softOperation(request, *args, **kwargs):
    """
        url: '/software/operate/',
        method: 'post',
    :param request:
    inputData: {
            token: data.token, // 用户的秘钥
            softwareVersionId: data.softwareVersionId,//软件id
            //用户相关操作
            operation: data.operation,  //管理人员：相关操作，0表示审核，1表示删除，2表示恢复，3表示发布(上线)，4表示下线，5表示下载
                                        //开发人员：，0恢复, 1删除
                                        //使用人员，0软件下载
                                        //管理人员审核操作
            orderId:
            verify: data.verify,        //审核结果 0:通过；1：不通过
            //管理人员上线操作相关
            isApply: data.isApply,          //0:开放权限，1：不开放,
            deliveryType: data.deliveryType,//物流列表,0:下载；1：光盘, 2:硬盘
        },
    :return:
    resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'softwareUrl': null,//只有下载有，其他返回
        }
    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # print(requestParam)
    user = datacheck.getUser(requestParam["token"])
    #  userType
    userType = user.userType

    # 软件版本 软件
    softwareVersion = SoftwareVersion.objects.filter(pk=requestParam['softwareVersionId'])
    softwareVersionItem = softwareVersion[0]
    software = softwareVersionItem.software
    # 开发人员
    if userType == '1':
        if requestParam["operation"] == 0:
            # 恢复
            softwareVersionItem.softwareState = '0'
            softwareVersionItem.save()
        elif requestParam["operation"] == 1:
            # 删除
            softwareVersionItem.softwareState = '1'
            softwareVersionItem.save()
    # 仓库管理人员
    elif userType == '2':
        if requestParam["operation"] == 0:
            if requestParam['verify'] == '0':
                softwareVersionItem.examineState = '1'
                softwareVersionItem.isExamine = True
                datalist = SoftwareData.objects.filter(softwareVersion=softwareVersionItem)
                for data in datalist:
                    data.dataCheckState = '1'
                    data.save()
                for company in json.loads(requestParam['isView']):
                    companys = Company.objects.filter(pk=company)
                    companyItem = companys[0]
                    softwareVersionItem.isBrowse.add(companyItem)
                for company in json.loads(requestParam['isDownload']):
                    companys = Company.objects.filter(pk=company)
                    companyItem = companys[0]
                    softwareVersionItem.isDownload.add(companyItem)
                softwareVersionItem.save()
                createAnnouncement(
                    userId=user.id,
                    type='software',
                    num='1',
                    userType='123',
                    softwareVersionId=softwareVersionItem.id,
                )
                # pdb.set_trace()

                for QAFileItem in softwareVersionItem.qaFile.all():
                    try:
                        xl = xlrd.open_workbook(QAFileItem.filePath)
                        table = xl.sheets()[0]  # 获取excel表
                        nrows = table.nrows
                        hang = nrows - 1
                        num = 1
                        while num <= hang:
                            question = table.cell(num, 0).value  # 读取某一单元格的值
                            handle = table.cell(num, 1).value
                            questionItem = SoftwareQuestion.objects.create(
                                softwareVersion=softwareVersionItem,
                                title='预留问题',
                                questionContent=question,
                                ishandle=True,
                                user=softwareVersionItem.user,
                                questionState=1
                            )
                            handlecontent = QuestionHandle.objects.create(
                                user=softwareVersionItem.user,
                                question=questionItem,
                                handleContent=handle,
                            )
                            num = num + 1
                    except:
                        pass
                if requestParam['isApply'] == '0':
                    softwareVersionItem.isApply = True
                    # 开放权限手动设置为 自由下载
                    softwareVersionItem.deliveryType = '3'
                    softwareVersionItem.save()
                elif requestParam['isApply'] == '1':
                    # 不开放权限 按照管理员设置为 其余选项
                    softwareVersionItem.isApply = False
                    softwareVersionItem.deliveryType = requestParam['deliveryType']
                    softwareVersionItem.save()
                option = "用户 " + user.username + "通过软件 [" + softwareVersionItem.softwareName + "] 版本:" + softwareVersionItem.version + "审核"
                createLog.createLog(option, softwareVersionItem.id, user.id)
            elif requestParam['verify'] == '1':
                softwareVersionItem.examineState = '2'
                softwareVersionItem.isExamine = True
                # get softwareVersionItem.softwareResult
                softwareVersionItem.softwareResult = requestParam['rejectReason']
                softwareVersionItem.save()
                datalist = SoftwareData.objects.filter(softwareVersion=softwareVersionItem)
                for data in datalist:
                    data.dataCheckState = '2'
                    data.save()
                createAnnouncement(
                    userId=user.id,
                    type='software',
                    num='2',
                    userType='12',
                    softwareVersionId=softwareVersionItem.id,
                )
                option = "用户 " + user.username + "未通过软件 [" + softwareVersionItem.softwareName + "] 版本:" + softwareVersionItem.version + "审核"
                createLog.createLog(option, softwareVersionItem.id, user.id)
            else:
                data = {
                    'code': 1,
                    'msg': 'verify error',
                    'softwareUrl': '',
                }
                logger_request.info(data)
        elif requestParam["operation"] == 1:
            # 删除
            softwareVersionItem.softwareState = '1'
            softwareVersionItem.save()
        elif requestParam["operation"] == 2:
            # 恢复
            softwareVersionItem.softwareState = '0'
            softwareVersionItem.save()
        elif requestParam["operation"] == 3:
            # 上线
            softwareVersionItem.isOnline = True
            softwareVersionItem.save()
            createAnnouncement(
                userId=user.id,
                type='software',
                num='3',
                userType='23',
                softwareVersionId=softwareVersionItem.id,
            )
        elif requestParam["operation"] == 4:
            softwareVersionItem.isOnline = False
            # softwareVersionItem.isApply = False
            softwareVersionItem.save()
            createAnnouncement(
                userId=user.id,
                type='software',
                num='4',
                userType='2',
                softwareVersionId=softwareVersionItem.id,
            )
        elif requestParam["operation"] == 5:

            # 下载
            if softwareVersionItem.deliveryType == '0':
                # file = softwareVersionItem.file
                file = FileStore.objects.filter(pk=requestParam["softFileId"]).first()
                if file.exists():
                    # 创建订单
                    createOrder(softwareVersionItem.id, user.id, softwareVersionItem.deliveryType,
                                softFileId=requestParam["softFileId"])
                    isValid, msg = download(file.fileName, "file", file.filePath, id=requestParam['softFileId'])
                    if isValid:
                        option = "用户 " + user.username + "下载了软件 [" + softwareVersionItem.softwareName + "] 版本:" + softwareVersionItem.version
                        createLog.createLog(option, softwareVersionItem.id, user.id)
                        data = {
                            'code': 0,
                            'msg': 'success',
                            'softwareUrl': msg,
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                    else:
                        data = {
                            'code': 1,
                            'msg': 'Error',
                            'softwareUrl': msg,
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                else:
                    data = {
                        'code': 1,
                        'msg': 'Error',
                        'softwareUrl': "File not exist",
                    }
                    logger_request.info(data)
                    return JsonResponse(data)
            else:
                pass
        else:
            pass
    else:
        if requestParam["operation"] == 0 and softwareVersionItem.examineState == '1':
            # 创建订单
            limit = False
            # orderId == ''
            if requestParam['orderId'] == '':
                createOrder(softwareVersionItem.id, user.id, softwareVersionItem.deliveryType,
                            softFileId=requestParam["softFileId"])
            else:
                order = SoftwareOrder.objects.filter(pk=requestParam['orderId'])
                orderItem = order[0]
                if orderItem.user == user and orderItem.isDownload and orderItem.isExamine:
                    limit = True
            # 下载
            if softwareVersionItem.deliveryType == '3' or limit:
                # file = softwareVersionItem.file
                fileList = FileStore.objects.filter(pk=requestParam["softFileId"])
                if fileList.exists():
                    file = fileList[0]
                    isValid, msg = download(file.fileName, "file", file.filePath, id=requestParam["softFileId"])
                    if isValid:
                        option = "用户 " + user.username + "下载了软件 [" + softwareVersionItem.softwareName + "] 版本:" + softwareVersionItem.version
                        createLog.createLog(option, softwareVersionItem.id, user.id)
                        data = {
                            'code': 0,
                            'msg': 'success',
                            'softwareUrl': msg,
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                    else:
                        data = {
                            'code': 1,
                            'msg': 'Error',
                            'softwareUrl': msg,
                        }
                        logger_request.info(data)
                        return JsonResponse(data)
                else:
                    data = {
                        'code': 1,
                        'msg': 'Error',
                        'softwareUrl': "File not exist",
                    }
                    logger_request.info(data)
                    return JsonResponse(data)
            else:
                pass
        else:
            data = {
                'code': 1,
                'msg': 'examineState Error',
                'softwareUrl': '',
            }
            logger_request.info(data)
            return JsonResponse(data)
    data = {
        'code': 0,
        'msg': 'success',
        'softwareUrl': '',
    }
    logger_request.info(data)
    return JsonResponse(data)


# 软件筛选、搜索
def softSearch(request, *args, **kwargs):
    """
            url: '/software/research/',
            method: 'post',
        :param request:
        inputData: {
            token: data.token,//用户密钥
            softwareName: data.software,        //搜索软件名称  软件
            storehouseId: data.storehouseId,    //仓库id        管理员 软件
            uploadStartTime: data.uploadTime,   //起始时间,时间戳  版本
            uploadEndTime: data.uploadTime,     //结束时间,时间戳  版本
            examineState: data.examineState,    //软件状态 0：未审核，1：审核通过，2：未通过（软件已删除组中此参数一直为‘’） 版本
            softwareGroup: data.softwareGroup,  //管理人员 0: 所有(包括审核已通过、未通过、未审核) 1：已删除               版本
                                                //开发人员 0: 已审核(包括审核已通过、未通过)，1：未审核，2：归档           版本
                                                //使用人员  0 自由下载
        },
        :return:
        resData: {
            'code': null, // 标志返回状态、0：成功 1：失败
            'msg': null, // 返回消息
            'softwarelist': [{
                'softwareId': null,
                'softwareName': null,
                'iconUrl': null,//软件图标
                'userName': null,//软件上传用户
                'softwareType': null,//软件类型
                'uploadTime': null,//软件上传时间
                'softwareDetails': null,//软件描述
                'size': null,//软件大小
                'softwareState': null,//软件状态
                'material': [{
                    'materialName': null,
                    'materialUrl': null,
                }],//软件详情资料
                'vesionList': [{
                    'vesionId': null,//版本id
                    'vesionName': null,
                }]

            }]
        }
        """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = datacheck.getUser(requestParam["token"])
    #  userType
    userType = user.userType
    # 从数据库获取软件时的filter条件字典
    filterDict = {}
    # 开发人员 todo 只能看本仓库的
    if userType == '1':
        filterDict['user'] = user
        # 已审核(包括审核已通过、未通过)
        if requestParam['softwareGroup'] == '0':
            filterDict['isExamine'] = True
            filterDict['softwareState'] = '0'
            # 软件状态 0：未审核，1：审核通过，2：未通过（软件已删除组中此参数一直为‘’）
            if requestParam['examineState'] in ['1', '2']:
                if requestParam['examineState'] == '1':
                    filterDict['examineState'] = '1'
                else:
                    filterDict['examineState'] = '2'
        # 1：未审核
        elif requestParam['softwareGroup'] == '1':
            filterDict['isExamine'] = False
            filterDict['softwareState'] = '0'
        # 归档的
        elif requestParam['softwareGroup'] == '2':
            filterDict['softwareState'] = '1'
        else:
            data = {
                'code': 1,
                'msg': 'softwareGroup Error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    # 仓库管理人员 todo 多个仓库
    elif userType == '2':
        # 0: 所有(包括审核已通过、未通过、未审核) 1：已删除
        if requestParam['softwareGroup'] == '0':
            # 未审核
            if requestParam['examineState'] == '0':
                filterDict['isExamine'] = False
                filterDict['softwareState'] = '0'
            # 已审核通过
            elif requestParam['examineState'] == '1':
                filterDict['isExamine'] = True
                filterDict['softwareState'] = '0'
                filterDict['examineState'] = '1'
            # 已审核未通过
            elif requestParam['examineState'] == '2':
                filterDict['isExamine'] = True
                filterDict['softwareState'] = '0'
                filterDict['examineState'] = '2'
        elif requestParam['softwareGroup'] == '1':
            filterDict['softwareState'] = '1'
        else:
            data = {
                'code': 1,
                'msg': 'softwareGroup Error',
            }
            logger_request.info(data)
            return JsonResponse(data)
        if requestParam['storehouseId'] != '':
            filterDict['software__store__id'] = requestParam['storehouseId']
    # 使用人员
    elif userType == '3':
        filterDict['isBrowse'] = user.company
        if requestParam['softwareGroup'] != '':
            if requestParam['softwareGroup'] == '0':
                filterDict['deliveryType'] = '3'
    else:
        data = {
            'code': 1,
            'msg': 'userType Error',
        }
        logger_request.info(data)
        return JsonResponse(data)

    # 进行筛选
    # if requestParam['uploadStartTime'] != '' and requestParam['uploadEndTime'] != '':
    #     filterDict['uploadTime__gte'] = requestParam['uploadStartTime']
    #     filterDict['uploadTime__lte'] = requestParam['uploadEndTime']
    if requestParam['softwareName'] != '':
        filterDict['softwareName__icontains'] = requestParam['softwareName']
    if requestParam['softwareTypeId'] != None:
        filterDict['softwareType'] = requestParam['softwareTypeId']
    softwareVersion = SoftwareVersion.objects.filter(**filterDict).order_by('-createTime')
    softwareList = []
    # 临时存储
    softwareDict = {}
    # todo url 细节
    for softwareVersionItem in softwareVersion:
        if softwareVersionItem.software.id not in softwareDict.keys():
            # 资料状态
            softwareData = SoftwareData.objects.filter(softwareVersion=softwareVersionItem).filter()
            # 多对多查询
            materialList = []
            tempVersion = []
            for dataItem in softwareData:
                item = {
                    'materialName': dataItem.dataName,
                    'materialUrl': download(dataItem.file.fileName, 'material', dataItem.file.filePath)[1]
                }
                materialList.append(item)
            versionList = {
                'versionId': softwareVersionItem.id,
                'versionName': softwareVersionItem.version
            }
            tempVersion.append(versionList)
            if softwareVersionItem.softwareState == '1':
                state = ''
            else:
                state = softwareVersionItem.examineState
            softwareItem = {
                'softwareId': softwareVersionItem.software.id,
                'softwareName': softwareVersionItem.softwareName,
                'iconUrl': download(softwareVersionItem.logo.fileName, 'logo',
                                    softwareVersionItem.logo.filePath)[1],
                'userName': softwareVersionItem.software.user.name,
                'softwareType': softwareVersionItem.softwareType.softwareType,
                'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
                'softwareDetails': softwareVersionItem.updateDetails,
                'currentVersionDesc': softwareVersionItem.currentVersionDesc,
                # 'size': softwareVersionItem.file.size,
                'size': tolist(softwareVersionItem.file.all(), False),
                'softwareState': state,
                'isOnline': softwareVersionItem.isOnline,
                'isOwn': 'todo',
                'material': materialList,
                'versionList': tempVersion,
                'storehouseName': softwareVersionItem.store.storehouseName,
                'rejectReason': softwareVersionItem.softwareResult
            }
            softwareDict[softwareVersionItem.software.id] = softwareItem
        else:
            versionList = {
                'versionId': softwareVersionItem.id,
                'versionName': softwareVersionItem.version
            }
            softwareDict[softwareVersionItem.software.id]['versionList'].append(versionList)
    for value in softwareDict.values():
        softwareList.append(value)
    totalNum = len(softwareList)
    result = softwareList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                   requestParam[
                                                                                                       'page'] *
                                                                                                   requestParam[
                                                                                                       'maxItem'])]
    data = {
        'code': 0,
        'msg': 'success',
        'totalNum': totalNum,
        'softwareList': result
    }
    logger_request.info(data)
    return JsonResponse(data)


def detailGet(request, *args, **kwargs):
    """
        url    : /software/softUpdate/',
        method : POST

        inputData: {
            token: data.token, // 用户的秘钥
            softwareVersionId: data.softversionid,//软件版本id
        },
        # 默认最新版本的
        resData: {
            'code': null,// 标志返回状态、0：成功，1：失败
            'msg': null,// 返回消息
            'softwareName': null,//
            'uploadTime': null,//
            'userName': null,//软件上传用户
            'softwareType': null,//软件类别
            'softwareState': null,//软件状态
            'softwareDetails': null,//软件描述
            'upCompany': null,//研发单位
            'size': null,//软件大小
            'iconUrl': null,//图标url
            'softUrl': null,//软件url
            'softwareDetails': null,
            'coverUrl': null,//封面url
            'versionList': [{
                'vesionId': null,//版本id
                'vesionName': null,//版本名称
            }]
            file {
                fileName
                fileUrl
            }
            //////////////////增加参数//////////////////////////////////////
            'rejectReason':null,//拒绝理由
            'cost':'',//计费

            'verification':[{'fileName':null,'fileUrl':null}],//查杀证明 文件名称（需要有文件后缀xx.xxx） 文件类型

            'QAFile':[{'fileName':null,'fileUrl':null}],//QA文件 文件名称后加后缀
        }
    }

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()
    user = datacheck.getUser(requestParam["token"])
    userType = user.userType
    # 软件版本 软件
    softwareVersion = SoftwareVersion.objects.filter(pk=requestParam['softwareVersionId'])
    software = softwareVersion[0].software

    softwareVersionItem = softwareVersion[0]

    # versionList
    versionList = []
    fileList = []
    version = {
        'versionId': softwareVersionItem.id,
        'versionName': softwareVersionItem.version,
    }
    versionList.append(version)
    # other Version
    versions = SoftwareVersion.objects.filter(software=software)
    versionAll = []
    for item in versions:
        version = {
            'versionId': item.id,
            'versionName': item.version,
        }
        versionAll.append(version)
    # all Data
    currentVersionAllData = SoftwareData.objects.filter(softwareVersion=softwareVersion[0])
    for currentVersionData in currentVersionAllData:
        file = {
            'id': currentVersionData.file.id,
            'dataId': currentVersionData.id,
            'dataName': currentVersionData.file.fileName,
            'fileUrl': download(currentVersionData.file.fileName, 'material', currentVersionData.file.filePath)[1],
        }
        fileList.append(file)
    # todo 需要的是什么信息
    if softwareVersionItem.softwareState == '1':
        state = ''
    else:
        state = softwareVersionItem.examineState

    # todo now one verification
    verificationList = [
        {
            'id': softwareVersionItem.verification.id,
            'fileName': softwareVersionItem.verification.fileName,
            'fileUrl': download(softwareVersionItem.verification.fileName, 'verification',
                                softwareVersionItem.verification.filePath)[1],
        }
    ]

    # QAFile
    QAFileList = []
    for QAFileItem in softwareVersionItem.qaFile.all():
        item = {
            'id': QAFileItem.id,
            'fileName': QAFileItem.fileName,
            'fileUrl': download(QAFileItem.fileName, 'QAFile',
                                QAFileItem.filePath)[1],
        }
        QAFileList.append(item)

    TypeList = []
    item = {
        'name': softwareVersionItem.softwareType.softwareType,
        'id': softwareVersionItem.softwareType.id,
    }
    TypeList.append(item)

    companyList = []
    item = {
        'name': softwareVersionItem.designUnit.name,
        'id': softwareVersionItem.designUnit.id,
    }
    companyList.append(item)

    warZoneList = []
    item = {
        'name': softwareVersionItem.designUnit.warZone.name,
        'id': softwareVersionItem.designUnit.warZone.id,
    }
    warZoneList.append(item)

    storeList = []
    item = {
        'name': softwareVersionItem.store.storehouseName,
        'id': softwareVersionItem.store.id,
    }
    storeList.append(item)

    iconList = []
    item = {
        'url': download(softwareVersionItem.logo.fileName, 'logo', softwareVersionItem.logo.filePath)[
            1],
        'id': softwareVersionItem.logo.id,
    }
    iconList.append(item)

    coverList = []
    item = {
        'url':
            download(softwareVersionItem.cover.fileName, 'cover', softwareVersionItem.cover.filePath)[
                1],
        'id': softwareVersionItem.cover.id,
    }
    coverList.append(item)

    softwareList = tolist(softwareVersionItem.file.all(), True)
    # item = {
    # 'url': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[1],
    # 'url': tolist(softwareVersionItem.file.all(), True),
    # 'id': softwareVersionItem.file.id,
    # 'name': softwareVersionItem.file.fileName,
    # }
    # softwareList.append(item)

    data = {
        'code': 0,
        'msg': 'success',
        'softwareName': softwareVersionItem.softwareName,
        'uploadTime': softwareVersionItem.uploadTime.strftime('%Y-%m-%d %H:%M:%S'),
        'userName': softwareVersionItem.user.name,
        'softwareType': TypeList,
        'softwareState': state,
        'softwareDetails': softwareVersionItem.updateDetails,
        'currentVersionDesc': softwareVersionItem.currentVersionDesc,
        'upCompany': companyList,
        'warZone': warZoneList,
        'iconUrl': iconList,
        'softList': tolist(softwareVersionItem.file.all(), True),
        # 'softUrl': download(softwareVersionItem.file.fileName, 'file', softwareVersionItem.file.filePath)[1],
        # 'size': softwareVersionItem.file.size,
        'coverUrl': coverList,
        'versionList': versionList,
        'file': fileList,
        'isOnline': softwareVersionItem.isOnline,
        'storehouseName': storeList,
        'rejectReason': softwareVersionItem.softwareResult,
        'cost': softwareVersionItem.cost,
        'verification': verificationList,
        'deliveryType': softwareVersionItem.deliveryType,
        'QAFile': QAFileList,
        # 'software': softwareList
        'versionAll': versionAll
    }
    logger_request.info(data)
    return JsonResponse(data)


def requestQA(request, *args, **kwargs):
    '''
        url:'/software/requestQA/',
            method:'post',
            inputData:{
                token:data.token,//
            }
            resData:{
                url:null,//QA文件下载地址
            }
    '''
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])
    # pdb.set_trace()

    # uploadUser userType
    userType = user.userType

    if userType == '1':
        # url = 'C:/360Downloads/ck/data/software/questionAnswer/QA.excel'
        # url = download('QA.xlsx', 'QAFile', 'C:/360Downloads/ck/data/software/questionAnswer/QA.xlsx')[1]
        url = download('QA.xlsx', 'QAFile', '/data/software/questionAnswer/QA.xlsx')[1]
        # url = 'C:/360Downloads/ck/data/software/questionAnswer/QA.excel'        
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
            'url': ''
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "url": url,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getDuanInfo(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])
    versionList = SoftwareVersion.objects.filter(pk=requestParam['softwareVersionId'])
    if not versionList.exists():
        data = {
            "code": 0,
            "msg": "success",
            "duanInfo": "",
        }
        logger_request.info(data)
        return JsonResponse(data)
    version = versionList[0]
    duanList = DuanInfo.objects.filter(softwareVersion=version).order_by('-duanVersion')
    duanInfo = []
    for duan in duanList:
        downloadUrl = ""
        if user.userType != 3:
            downloadUrl = download(duan.file.fileName, 'file', duan.file.filePath)[1]
        dictItem = {
            "id": duan.id,
            "type": duan.type,
            "duanName": duan.duanName,
            "duanDesc": duan.duanDesc,
            "duanPrefix": duan.duanPrefix,
            "duanVersion": duan.duanVersion,
            "duanType": duan.duanType,
            "cpuType": duan.cpuType,
            "developUnit": duan.developUnit,
            "createTime": duan.createTime.strftime('%Y-%m-%d %H:%M:%S'),
            "downloadUrl": downloadUrl,
            "isLatest": duan.isLatest,
            "fileId": duan.file.id,
            "size": duan.file.size
        }
        duanInfo.append(dictItem)
    data = {
        "code": 0,
        "msg": "success",
        "duanInfo": duanInfo,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getDuanInfoServer(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    duanList = DuanInfo.objects.filter(isLatest=1).order_by('-duanVersion')
    duanInfo = []
    totalNum = len(duanList)
    result = duanList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                               requestParam[
                                                                                                   'page'] *
                                                                                               requestParam[
                                                                                                   'maxItem'])]
    for duan in result:
        downloadUrl = download(duan.file.fileName, 'file', duan.file.filePath)[1]
        dictItem = {
            "id": duan.id,
            "type": duan.type,
            "duanName": duan.duanName,
            "duanDesc": duan.duanDesc,
            "duanPrefix": duan.duanPrefix,
            "duanVersion": duan.duanVersion,
            "duanType": duan.duanType,
            "cpuType": duan.cpuType,
            "developUnit": duan.developUnit,
            "createTime": duan.createTime.strftime('%Y-%m-%d %H:%M:%S'),
            "downloadUrl": downloadUrl,
            "isLatest": duan.isLatest,
            "relateId": duan.realteId,
            "size": duan.file.size
        }
        duanInfo.append(dictItem)

    data = {
        "code": 0,
        "msg": "success",
        "duanInfo": duanInfo,
    }
    logger_request.info(data)
    return JsonResponse(data)


# server
def pushDuanToOther(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # user = datacheck.getUser(requestParam["token"])
    duan = DuanInfo.objects.filter(pk=requestParam['duanId']).first()
    # pprint(json.loads(duan.realteId))
    # pprint(duan.id)
    # pprint(duan.cpuType)
    find_relate_duan = FindRelateDuan(duan.cpuType)
    pushList = find_relate_duan.find_duan(duan.realteId, duan.id)
    pushList.reverse()
    logger_request.info(pushList)
    infoList = find_relate_duan.findUrlById(pushList)
    body = {
        "segList": infoList
    }
    url = serverInstallIp + ":" + serverInstallPort + serverPushUrl
    rec = requests.post(url, data=json.dumps(body))

    msg = json.loads(rec.text)
    try:
        if not msg["code"] == 200:
            data = {
                "code": 1,
                "msg": "error",
                "pushList": infoList,
            }
            logger_request.info(data)
            return JsonResponse(data)
    except Exception as e:
        data = {
            "code": 1,
            "msg": msg,
            "pushList": infoList,
        }
        logger_request.info(data)
        logger_request.info(msg)
        return JsonResponse(data)
    data = {
        "code": 0,
        "msg": "success",
        "pushList": infoList,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getPushList(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    filterDict = {}
    if requestParam["state"] != "":
        filterDict['pushState'] = requestParam["state"]
    pushList = PushOther.objects.filter(**filterDict).order_by('-createTime')
    totalNum = len(pushList)
    result = pushList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                               requestParam[
                                                                                                   'page'] *
                                                                                               requestParam[
                                                                                                   'maxItem'])]
    infoList = []
    for item in result:
        it = {
            "pushState": item.pushState,
            "createTime": item.createTime.strftime('%Y-%m-%d %H:%M:%S'),
            "duanName": item.duan.duanName,
            "duanPrefix": item.duan.duanPrefix,
            "duanDesc": item.duan.duanDesc,
            "duanVersion": item.duan.duanVersion,
            "pushMsg": item.msg
        }
        infoList.append(it)
    data = {
        'code': 0,
        'msg': 'success',
        'totalNum': totalNum,
        'infoList': infoList
    }
    logger_request.info(data)
    return JsonResponse(data)


def getPushState(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    poItem = PushOther.objects.filter(pk=requestParam['id'])
    if not poItem.exists():
        data = {
            'code': 0,
            'msg': 'error',
        }
        logger_request.info(data)
        return JsonResponse(data)
    item = poItem.first()
    item.pushState = requestParam['state']
    item.save()
    item.msg = requestParam['msg']
    item.save()

    data = {
        'code': 0,
        'msg': 'success',
    }
    logger_request.info(data)
    return JsonResponse(data)


def getHash(request, *args, **kwargs):
    '''
        url:'/software/hash/',
            method:'post',
            inputData:{
                token:data.token,//
            }
            resData:{
                url:null,//hash文件下载地址
            }
    '''
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    user = datacheck.getUser(requestParam["token"])
    # pdb.set_trace()

    # uploadUser userType
    userType = user.userType

    if userType == '1':
        # url = 'C:/360Downloads/ck/data/software/questionAnswer/QA.excel'
        # url = download('QA.xlsx', 'QAFile', 'C:/360Downloads/ck/data/software/questionAnswer/QA.xlsx')[1]
        url = download('hash.js', str(0), '/data/staticFile/develop/dist/hash.js')[1]
        # url = 'C:/360Downloads/ck/data/software/questionAnswer/QA.excel'        
    else:
        data = {
            'code': 1,
            'msg': 'userType error',
            'url': ''
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "url": url,
    }
    logger_request.info(data)
    return JsonResponse(data)


def tolist(querySet, needDown):
    if needDown:
        return [{
            "id": i.id,
            "size": i.size,
            "fileName": i.fileName,
            "fileUrl": download(i.fileName, "file", i.filePath)[1],
        } for i in querySet]
    else:
        return [{
            "id": i.id,
            "size": i.size,
            "fileName": i.fileName,
        } for i in querySet]
def save(request, *args, **kwargs):
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    user = User.objects.filter(username=requestParam['userName'])
    if user.exists():
        user1 = user[0]
        userData = {
            "name": user1.username,
            "createTime": user1.createTime
        }
    else:
        userData = {}

    data = {
        "code": 0,
        "msg": "success",
        "data": userData,
    }
    logger_request.info(data)
    return JsonResponse(data)